<template>
  <div class="doctor-management-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">医生信息管理</h2>
      <div class="action-buttons">
        <el-button type="primary" size="small" @click="openDialog('add')" class="add-btn">
          <el-icon><Plus /></el-icon>添加医生
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%; margin-top: 16px"
      v-loading="loading"
      class="doctor-table"
      :default-sort="{ prop: 'doc_id', order: 'ascending' }"
    >
      <el-table-column prop="doc_name" label="医生姓名" width="120" align="center" fixed />
      <el-table-column prop="sex" label="性别" width="80" align="center" />
      <el-table-column prop="nation" label="民族" width="100" align="center" />
      <el-table-column prop="work_year" label="工作年限" width="100" align="center" />
      <el-table-column prop="politicstatus" label="政治面貌" width="120" align="center" show-overflow-tooltip />
      <el-table-column prop="doc_title" label="职称" width="100" align="center" />
      <el-table-column prop="education" label="学历" width="100" align="center" />
      <el-table-column prop="introduction" label="简介" width="200" align="center" show-overflow-tooltip />
      <el-table-column prop="telephone" label="电话" width="120" align="center" />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-image
            :src="scope.row.img"
            style="width: 40px; height: 40px; border-radius: 4px;"
            fit="cover"
            :preview-src-list="[scope.row.img]"
            v-if="scope.row.img"
          />
          <span v-else class="no-avatar">无头像</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.recommend === 1 ? 'success' : 'info'" size="small" class="recommend-tag">
            {{ scope.row.recommend === 1 ? '已推荐' : '未推荐' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button-group class="action-buttons">
            <el-button 
              type="primary" 
              size="small" 
              @click="toggleRecommend(scope.row)"
              :class="scope.row.recommend === 1 ? 'cancel-recommend' : 'set-recommend'"
            >
              {{ scope.row.recommend === 1 ? '取消推荐' : '设为推荐' }}
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              plain
              @click="openDialog('edit', scope.row)"
              class="edit-btn"
            >
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              plain
              @click="handleDelete(scope.row.doc_id)"
              class="delete-btn"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 编辑/添加弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="680px"
      @close="resetForm"
      class="doctor-dialog"
    >
      <el-form
        ref="doctorForm"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医生ID" prop="doc_id">
              <el-input 
                v-model="form.doc_id" 
                placeholder="自动生成或手动输入" 
                :disabled="dialogType === 'edit'" 
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="医生姓名" prop="doc_name">
              <el-input v-model="form.doc_name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="民族" prop="nation">
              <el-input v-model="form.nation" placeholder="请输入民族" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作年限" prop="work_year">
              <el-input-number v-model="form.work_year" :min="0" :max="60" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政治面貌" prop="politicstatus">
              <el-input v-model="form.politicstatus" placeholder="请输入政治面貌" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职称" prop="doc_title">
              <el-input v-model="form.doc_title" placeholder="请输入职称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历" prop="education">
              <el-select v-model="form.education" placeholder="请选择学历" style="width: 100%">
                <el-option label="博士" value="博士" />
                <el-option label="硕士" value="硕士" />
                <el-option label="本科" value="本科" />
                <el-option label="大专" value="大专" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="简介" prop="introduction">
          <el-input 
            v-model="form.introduction" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入简介" 
            show-word-limit 
            maxlength="200" 
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="recommend">
              <el-switch 
                v-model="form.recommend" 
                :active-value="1" 
                :inactive-value="0" 
                active-text="推荐" 
                inactive-text="不推荐" 
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像" prop="img">
          <el-input v-model="form.img" placeholder="请输入头像URL" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="saveDoctor" class="confirm-btn">
            {{ dialogType === 'add' ? '确认添加' : '确认修改' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import axios from 'axios';

// 数据状态
const tableData = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogType = ref(''); // 'add' | 'edit'
const form = ref({});
const doctorForm = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表单验证规则
const rules = {
  doc_id: [{ required: true, message: '医生ID不能为空', trigger: 'blur' }],
  doc_name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  nation: [{ required: true, message: '民族不能为空', trigger: 'blur' }],
  work_year: [{ required: true, message: '工作年限不能为空', trigger: 'blur' }],
  politicstatus: [{ required: true, message: '政治面貌不能为空', trigger: 'blur' }],
  doc_title: [{ required: true, message: '职称不能为空', trigger: 'blur' }],
  education: [{ required: true, message: '学历不能为空', trigger: 'change' }],
  telephone: [
    { required: true, message: '电话不能为空', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  img: [{ required: true, message: '头像地址不能为空', trigger: 'blur' }]
};

onMounted(() => {
  fetchData();
});

const fetchData = () => {
  loading.value = true;
  axios.get('http://localhost:8080/hospital5_war/doctor/findAll')
    .then(res => {
      total.value = res.data.length;
      // 前端分页处理
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      tableData.value = res.data.slice(start, end);
      loading.value = false;
    })
    .catch(err => {
      console.error('数据获取失败：', err);
      loading.value = false;
      ElMessage.error('数据加载失败');
    });
};

const openDialog = (type, row = {}) => {
  dialogType.value = type;
  dialogVisible.value = true;
  if (type === 'edit') {
    form.value = { ...row };
  } else {
    form.value = { recommend: 0 }; // 初始未推荐
  }
};

const saveDoctor = () => {
  doctorForm.value.validate((valid) => {
    if (valid) {
      const request = dialogType.value === 'add' 
        ? axios.post('http://localhost:8080/hospital5_war/doctor/add', form.value) 
        : axios.post('http://localhost:8080/hospital5_war/doctor/update', form.value);
      
      request.then(res => {
        if (res.data.success) {
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
          fetchData();
        } else {
          ElMessage.error(res.data.message);
        }
      }).catch(err => {
        console.error('操作失败：', err);
        ElMessage.error('网络异常，请重试');
      });
    }
  });
};

const toggleRecommend = (row) => {
  const newRecommend = row.recommend === 1 ? 0 : 1;
  const updateData = { ...row, recommend: newRecommend };
  
  axios.post('http://localhost:8080/hospital5_war/doctor/update', updateData)
    .then(res => {
      if (res.data.success) {
        row.recommend = newRecommend; 
        ElMessage.success('推荐状态已更新');
      } else {
        ElMessage.error(res.data.message);
      }
    })
    .catch(err => {
      console.error('状态更新失败：', err);
      ElMessage.error('网络异常，请重试');
    });
};

const handleDelete = (docId) => {
  ElMessageBox.confirm(
    '此操作将永久删除该医生，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios.get(`http://localhost:8080/hospital5_war/doctor/delete?docId=${docId}`)
      .then(res => {
        if (res.data.success) {
          ElMessage.success('删除成功');
          fetchData();
        } else {
          ElMessage.error(res.data.message);
        }
      })
      .catch(err => {
        console.error('删除失败：', err);
        ElMessage.error('网络异常，请重试');
      });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

const resetForm = () => {
  form.value = {};
  if (doctorForm.value) {
    doctorForm.value.resetFields();
  }
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '添加医生' : '编辑医生信息';
});
</script>

<style scoped>
.doctor-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.add-btn {
  height: 32px;
  font-size: 14px;
}

.doctor-table {
  font-size: 14px;
}

.doctor-table :deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.doctor-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.no-avatar {
  color: #909399;
  font-size: 12px;
}

.recommend-tag {
  font-size: 12px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-btn, .delete-btn {
  padding: 7px 10px;
}

.set-recommend {
  background-color: #67c23a;
  border-color: #67c23a;
}

.cancel-recommend {
  background-color: #909399;
  border-color: #909399;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.doctor-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8;
  padding: 16px 20px;
  margin-right: 0;
}

.doctor-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.cancel-btn, .confirm-btn {
  width: 80px;
}
</style>